package com.md.album

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.bumptech.glide.Glide
import com.md.album.adapter.AlbumAdapter
import com.md.album.contracts.SelfAlbumContract
import com.md.album.databinding.FragmentCreateAlbumBinding
import com.md.album.db.SelfAlbumManager
import com.md.album.event.SelfAlbumEventModel
import com.md.album.event.SelfRefreshEvent
import com.md.album.presenter.SelfAlbumPresenter
import com.md.album.ui.*
import com.md.basedpc.log.Log
import com.md.basedpc.routerservice.NotifyService
import com.md.datastore.MysaveAlbumManager
import com.md.livingwidget.navigation.PHNavigationBar
import com.md.livingwidget.toast.PHToast
import com.md.network.api.Album
import com.md.network.api.Audio
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

const val ALBUM_ID = "ALBUM_ID"
const val ALBUM_TITLE = "ALBUM_TITLE"
const val IS_MINE = "IS_MINE"

/**
 * @author liyue
 * created 2021/3/21
 * desc 用于自建专辑/收藏页面，自建专辑音频从DB中获取，收藏专辑音频从网络请求
 */
class SelfAlbumFragment : Fragment(), PHNavigationBar.OnBarClickListener, SelfAlbumContract.View {
    private lateinit var binding: FragmentCreateAlbumBinding
    private lateinit var navBar: PHNavigationBar
    private lateinit var tvTitle: TextView
    private lateinit var tvTip3: TextView
    private lateinit var ivSave: ImageView
    private lateinit var ivDownload: ImageView
    private lateinit var ivShare: ImageView
    private lateinit var recAudio: RecyclerView
    private lateinit var ivAlbumCover: ImageView
    private lateinit var tvAlbumTitle: TextView
    private lateinit var tvAuthor: TextView
    private lateinit var tvProfile: TextView
    private lateinit var tvProfile2: TextView
    private lateinit var albumAdapter: AlbumAdapter
    private lateinit var lltEmpty: LinearLayout
    private lateinit var lltContainer: LinearLayout
    private var mPrestner = SelfAlbumPresenter()
    private var title = ""
    private var curAlbum: Album? = null
    private var isMine = true //是否自建专辑
    private var isSaved = true //当前Album是否被收藏


    companion object {
        fun newFragment(title: String, isMine: Boolean): SelfAlbumFragment {
            var fragment = SelfAlbumFragment()
            var bundle = Bundle()
            bundle.putString(ALBUM_TITLE, title)
            bundle.putBoolean(IS_MINE, isMine)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        binding = FragmentCreateAlbumBinding.inflate(LayoutInflater.from(activity))
        arguments?.let {
            title = it.getString(ALBUM_TITLE, "")
            this.isMine = it.getBoolean(IS_MINE, true)
        }

        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initNav()
        initView()
        mPrestner.attachView(this)
        if (isMine) {
            initData()
        } else {
            requestData()
        }
    }


    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        mPrestner.detachView()
        super.onDestroyView()
    }


    override fun onBarLeft1Back(v: View?) {

    }

    override fun onBarRight2Btn(v: View?) {

    }

    override fun onBarRight1Btn(v: View?) {

    }

    override fun onBarRight3Btn(v: View?) {

    }

    override fun onBarLeft2Back(v: View?) {

    }

    override fun onBarRight1Tv(v: View?) {

    }

    //先传入的数据后添加Fragment
    fun setAlbum(album: Album?) {
        this.curAlbum = album
    }

    private fun initData() {
        var audios = SelfAlbumManager.getIns().getAudiosByAlbumId(curAlbum!!.id)
        showAudios(audios)
    }

    private fun requestData() {
        var albumId = Integer.parseInt(curAlbum!!.id)
        if (albumId > 0) {
            mPrestner.getAlbum(albumId = albumId)
        }
    }

    private fun showAudios(audios: List<Audio>) {
        if (audios.isNotEmpty()) {
            lltEmpty.visibility = View.GONE
            recAudio.visibility = View.VISIBLE
            curAlbum?.audios?.addAll(audios)
            albumAdapter.setData(curAlbum, audios)
        } else {
            lltEmpty.visibility = View.VISIBLE
            recAudio.visibility = View.GONE
        }
    }

    private fun initNav() {
        navBar = binding.navBar
        navBar.toolbar.setBackgroundColor(resources.getColor(R.color.album_transform))
        navBar.root.setBackgroundColor(resources.getColor(R.color.album_transform))
        navBar.left1Imgback.apply {
            setImageResource(R.drawable.white_common_back)
            setOnClickListener { activity?.finish() }
        }
        tvTitle = navBar.centerTvTitle
        tvTitle.apply {
            text = getString(R.string.album_album)
            setTextColor(resources.getColor(R.color.album_color_white))
        }
    }

    private fun initView() {
        recAudio = binding.recAudio
        ivAlbumCover = binding.ivAlbumCover
        tvAlbumTitle = binding.tvAlbumTitle
        tvAlbumTitle.text = title
        tvAuthor = binding.tvAuthor
        tvProfile = binding.tvProfile
        tvProfile2 = binding.tvProfile2
        lltEmpty = binding.lltEmpty
        recAudio = binding.recAudio
        recAudio.layoutManager = LinearLayoutManager(activity!!)
        albumAdapter = AlbumAdapter(activity!!, isMine, ArrayList())
        recAudio.adapter = albumAdapter
        tvTip3 = binding.tvTip3
        lltContainer = binding.lltContainer
        ivSave = navBar.right1Btn
        if (isMine) {
            binding.cltProfile.setOnClickListener {
                var intent = Intent(activity, EditSelfAlbumActivity::class.java)
                intent.putExtra(TMP_TITLE, title)
                intent.putExtra(TMP_ALBUMID, curAlbum!!.id)
                activity!!.startActivity(intent)
            }
            lltContainer.setBackgroundResource(R.drawable.album_fragment_bg)
            tvProfile.apply {
                visibility = View.VISIBLE
                var desc =
                        if(TextUtils.isEmpty(curAlbum?.desc)) resources.getString(R.string.album_edit_profile)
                        else curAlbum?.desc
                text = desc
            }
            tvProfile2.visibility = View.GONE
            ivSave.visibility = View.GONE
        } else {
            lltContainer.setBackgroundColor(resources.getColor(R.color.album_578D7B))
            tvProfile2.apply {
                visibility = View.VISIBLE
                text = curAlbum?.desc
            }
            tvProfile.visibility = View.GONE
            ivSave.apply {
                visibility = View.VISIBLE
                setImageDrawable(resources.getDrawable(R.drawable.album_save))
//                var savedDB = MysaveAlbumManager.getIns().getAlbumDBById(curAlbum?.id)
//                if (savedDB !=null){
                setColorFilter(ContextCompat.getColor(context, R.color.album_ff3333), android.graphics.PorterDuff.Mode.SRC_IN)
//                }else{
//                    setColorFilter(ContextCompat.getColor(context, R.color.white), android.graphics.PorterDuff.Mode.SRC_IN)
//                }
                setOnClickListener {
                    isSaved = !isSaved
                    //未收藏变收藏
                    var isSuc = false
                    if (isSaved) {
                        isSuc = MysaveAlbumManager.getIns().saveAlbum(curAlbum)
                        if (isSuc) {
                            ARouter.getInstance().navigation(NotifyService::class.java).selfAlbumUpdateSuc(0x2)// 收藏的专辑，目前传的值还没用
                            PHToast.showSingleToast(activity,getString(R.string.album_save_suc))
                        }
                    } else { //收藏变未收藏
                        isSuc = MysaveAlbumManager.getIns().deleteAlbumById(curAlbum?.id)
                        if (isSuc){
                            ARouter.getInstance().navigation(NotifyService::class.java).selfAlbumUpdateSuc(0x2)// 收藏的专辑，目前传的值还没用
                            PHToast.showSingleToast(activity,getString(R.string.album_delete_suc))
                        }
                    }
                    //如果处理未成功，isSaved恢复原状态
                    if (!isSuc){
                        isSaved = !isSaved
                    }

                    if (isSaved) {
                        setColorFilter(ContextCompat.getColor(context, R.color.album_ff3333), android.graphics.PorterDuff.Mode.SRC_IN)
                    } else {
                        setColorFilter(ContextCompat.getColor(context, R.color.white), android.graphics.PorterDuff.Mode.SRC_IN)
                    }
                }
            }
        }
        tvTip3.setOnClickListener {
            var intent = Intent(activity, SelectSelfAlbumActivity::class.java)
            intent.putExtra(CURRENT_ALBUM_ID, curAlbum!!.id)
            startActivity(intent)
        }
        curAlbum?.coverUrl?.let {
            activity?.let { it1 ->
                Glide.with(it1)
                        .load(curAlbum!!.coverUrl)
                        .placeholder(R.drawable.selfalbum_cover_default)
                        .into(ivAlbumCover)
            }
        }

    }


    /**
     * 自建专辑名称、描述被改变了才会被调用。
     * 收藏专辑有变化不会调用此方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    override fun showProfile(mode: SelfAlbumEventModel) {
        mode?.let {
            tvAlbumTitle.text = mode.title
            tvProfile.text = mode.desc
            Glide.with(this)
                    .load(mode.coverPath)
                    .into(ivAlbumCover)
        }

    }

    /**
     * 自建专辑内音频增加或删除会通过EventBus调用
     * 收藏专辑变化不会调用此方法
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    override fun showAudios(model: SelfRefreshEvent) {
        if (isMine){
            var audios = SelfAlbumManager.getIns().getAudiosByAlbumId(curAlbum!!.id)
            if (audios.isNotEmpty()) {
                lltEmpty.visibility = View.GONE
                recAudio.visibility = View.VISIBLE
                albumAdapter.setData(curAlbum, audios)
            } else {
                lltEmpty.visibility = View.VISIBLE
                recAudio.visibility = View.GONE
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshIcon(model: SelectCoverModel) {
//        if (model.isSave){
//                Glide.with(this)
//                        .load(model.resUrl)
//                        .into(ivAlbumCover)
//                curAlbum?.coverUrl = model.resUrl
//                SelfAlbumManager.getIns().saveAlbum(curAlbum)
//        }
    }

    override fun showError(errorMsg: String) {
        Log.e(errorMsg)
    }

    override fun showAlbumInfo(album: Album?) {
        var audios = album?.audios
        audios?.let {
            showAudios(it)
        }
    }
}